<template>
  <div :class="prefixCls">
    <quill-editor
      class="quill-top"
      v-model="content"
      ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @ready="onEditorReady($event)"
      @change="onEditorChange($event)"
    ></quill-editor>

    <el-upload
      accept=".jpg, .png, .jpeg, .gif"
      class="editor-upload"
      action="https://jsonplaceholder.typicode.com/posts/"
      :file-list="fileList"
      :on-remove="handleRemove"
      :http-request="customRequest"
      :on-change="handleChange"
    >
      <el-button>
        <i class="el-icon-upload" />点击选择文件上传
      </el-button>
    </el-upload>
    <el-upload
      accept=".mp4, .avi, .rmvb"
      class="editor-video-upload"
      action="https://jsonplaceholder.typicode.com/posts/"
      :file-list="videoFile"
      :on-remove="handleRemove"
      :http-request="videoRequest"
      :on-change="handleChange"
    >
      <el-button>
        <i class="el-icon-upload" />点击选择文件上传
      </el-button>
    </el-upload>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
import { saveOnlyUploads } from '@/api/supplier'

export default {
  name: 'QuillEditor',
  components: {
    quillEditor
  },
  props: {
    prefixCls: {
      type: String,
      default: 'ant-editor-quill'
    },
    // 表单校验用字段
    // eslint-disable-next-line
    value: {
      type: String
    },
    show: {
      type: String,
      default: null
    },
    placeholder: {
      type: String,
      default: '请输入Sql语句'
    }
  },
  data() {
    // 工具栏配置
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'], // toggled buttons
      ['blockquote', 'code-block'],

      [{ header: 1 }, { header: 2 }], // custom button values
      [{ list: 'ordered' }, { list: 'bullet' }],
      [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
      [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
      [{ direction: 'rtl' }], // text direction

      [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
      [{ header: [1, 2, 3, 4, 5, 6, false] }],

      [{ color: [] }, { background: [] }], // dropdown with defaults from theme
      [{ font: [] }],
      [{ align: [] }],
      ['link', 'image', 'video'],
      ['clean'] // remove formatting button
    ]
    return {
      fileList: [],
      videoFile: [],
      content: this.show,
      editorOption: {
        theme: 'snow',
        placeholder: this.placeholder,
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  console.log('自定义图片')
                  document.querySelector('.editor-upload .el-button').click()
                } else {
                  this.quill.format('image', false)
                }
              },
              video: function(value) {
                if (value) {
                  console.log('自定义视频')
                  document.querySelector('.editor-video-upload .el-button').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }

        // some quill options
      }
    }
  },
  methods: {
    onEditorBlur(quill) {
      // console.log('editor blur!', quill)
      this.$emit('blur', quill)
    },
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    onEditorReady(quill) {
      // console.log('editor ready!', quill)
    },
    onEditorChange({ quill, html, text }) {
      console.log('editor change!', quill, html, text)
      this.$emit('change', text, html)
    },
    handleChange(file, fileList) {
      console.log('change', file, fileList)
      //   this.fileList = fileList.slice(-2)
    },
    // 删除图片事件处理
    handleRemove(file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传图片事件处理
    customRequest(info, fileList) {
      console.log('customRequest', info, fileList)
      const formData = new FormData()
      formData.append('file', info.file)

      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      console.log('组件实例', quill)

      // this.fileList = []
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          this.fileList.push(data)
          // this.fileList[this.fileList.length - 1].status = 'done'
          this.fileList[this.fileList.length - 1].url = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].savePath = data.fileUrl + data.fileName
          this.fileList[this.fileList.length - 1].name = data.uploadTitle
          this.fileList[this.fileList.length - 1].attachmentName = data.uploadTitle

          console.log('fileList', this.fileList)

          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'image', data.fileUrl + data.fileName)
          // 调整光标到最后
          quill.setSelection(length + 1)

          console.log('content', this.content)
        }
      })
    },
    // 上传视频事件处理
    videoRequest(info, fileList) {
      console.log('customRequest', info, fileList)
      const formData = new FormData()
      formData.append('file', info.file)

      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      console.log('组件实例', quill)

      // this.videoFile = []
      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          this.videoFile.push(data)
          this.videoFile[this.videoFile.length - 1].url = data.fileUrl + data.fileName
          this.videoFile[this.videoFile.length - 1].savePath = data.fileUrl + data.fileName
          this.videoFile[this.videoFile.length - 1].name = data.uploadTitle
          this.videoFile[this.videoFile.length - 1].attachmentName = data.uploadTitle

          console.log('fileList', this.videoFile)

          // 获取光标所在位置
          let length = quill.getSelection().index
          // 插入图片，res为服务器返回的图片链接地址
          quill.insertEmbed(length, 'video', data.fileUrl + data.fileName)
          // 调整光标到最后
          quill.setSelection(length + 1)

          console.log('content', this.content)
        }
      })
    }
  },
  watch: {
    value(val) {
      this.content = val
    }
  }
}
</script>

<style lang="less" scoped>
@import url('../index.less');

/* 覆盖 quill 默认边框圆角为 ant 默认圆角，用于统一 ant 组件风格 */
.ant-editor-quill {
  /deep/ .ql-toolbar.ql-snow {
    border-radius: @border-radius-base @border-radius-base 0 0;
  }
  /deep/ .ql-container.ql-snow {
    border-radius: 0 0 @border-radius-base @border-radius-base;
  }
}

.editor-upload {
  display: none;
}
.editor-video-upload {
  display: none;
}
</style>

<style scoped>
.quill-top >>> .ql-snow .ql-editor {
  height: 300px;
}
</style>

